/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int tj_directory_current(char* buffer) {
	getcwd(buffer, 255);
	return 0;
}

int tj_directory_name(char result[]) {
	int i;
	int last_s = 0;
	for (i = 0; i < strlen(result); i++) {
		if ('/' == result[i]) {
			last_s = i;
		}
	}
	result[last_s] = '\0';
	return last_s;
}

int tj_path_real(char *path, char* result) {
	char* temp = realpath(path, NULL);
	if (NULL == temp) {
		char root_path[255] = { '\0' };
		tj_directory_current(root_path);
		printf("real path error : pwd => '%s' file => '%s'. \n", root_path, path);
		return -1;
	}
	strcpy(result, temp);
	return 0;
}

int tj_path_exists(char *filename) {
	char real_path[255] = { '\0' };
	if (tj_path_real(filename, real_path)) {
		return -1;
	}
	return access(real_path, 0);
}

int tj_path_is_file(char* path) {
	char real_path[255] = { '\0' };
	if (tj_path_real(path, real_path)) {
		return -1;
	}
	struct stat sb;
	if (lstat(real_path, &sb)) {
		printf("Gives information about The file '%s' error. \n", real_path);
		return -1;
	}
	if (S_ISREG(sb.st_mode)) {
		return 0;
	}
	return -1;
}

int tj_path_is_directory(char* path) {
	char real_path[255] = { '\0' };
	if (tj_path_real(path, real_path)) {
		return -1;
	}
	struct stat sb;
	if (lstat(real_path, &sb)) {
		printf("Gives information about The file '%s' error. \n", real_path);
		return -1;
	}
	if (S_ISDIR(sb.st_mode)) {
		return 0;
	}
	return -1;
}

int tj_path_is_symlink(char* path) {
	char real_path[255] = { '\0' };
	if (tj_path_real(path, real_path)) {
		return -1;
	}
	struct stat sb;
	if (lstat(real_path, &sb)) {
		printf("Gives information about The file '%s' error. \n", real_path);
		return -1;
	}
	if (S_ISLNK(sb.st_mode)) {
		return 0;
	}
	return -1;
}
